package u.hnx.admin.security.filter;

import cn.hutool.extra.spring.SpringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import u.hnx.admin.security.api.CaptchaFilter;

import java.io.IOException;
import java.util.Optional;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
        if (!request.getMethod().equalsIgnoreCase("post")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        CaptchaFilter captchaFilter = (CaptchaFilter) SpringUtil.getBean(CaptchaFilter.class);
        Optional.ofNullable(captchaFilter).ifPresent(n-> {
            try {
                n.check(request);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        });
        return super.attemptAuthentication(request, response);
    }
}
